﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharp.Study.Test
{
    public static class 异步练习
    {
        public static void Go()
        {
            string url = "https://aaa";
            //最大重试次数
            int maxTimes = 3;
            string html = DownloadHtmlByUrl(url, maxTimes).Result;
        }

        //封装一个异步方法，下载给定的网址，如果下载失败，等待500ms之后重试，如果重试三次还是失败，就抛出异常“下载失败”.
        public static async Task<string> DownloadHtmlByUrl(string url,int maxTimes)
        {         
            int delaySecounds = 500;
            string html = string.Empty;
            HttpClient client = new HttpClient();
            try
            {
                html = await client.GetStringAsync(url);
            }
            catch (Exception)
            {
            }           
            if (maxTimes == 0)
                throw new Exception("下载失败！");
            if (string.IsNullOrWhiteSpace(html))
            {
                await Task.Delay(delaySecounds);
                maxTimes--;
                await DownloadHtmlByUrl(url, maxTimes);
            }
            return html;
        }

    }
}
